package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-vgo/robotgo"
	"github.com/gorilla/websocket"
	"log"
)

type CursorMessage struct {
	T string  `json:"t"`
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

func DoCursorFunc(msg CursorMessage) {
	switch msg.T {
	case "move":
		robotgo.MoveRelative(int(msg.X*10), int(msg.Y*10))
	case "click_single":
		robotgo.Click()
	case "click_double":

	}
}

func ListenCursor(ctx context.Context) {
	// WebSocket服务器地址
	//server := "ws://localhost:8080/ws"
	server := "ws://118.178.239.213:8081/ws"
	// 连接到WebSocket服务器
	c, _, err := websocket.DefaultDialer.Dial(server, nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer func(c *websocket.Conn) {
		_ = c.Close()
	}(c)

	// 用于存储接收到的消息
	for {
		select {
		case <-ctx.Done():
			return
		default:
			messageType, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				break
			}
			fmt.Printf("Received: %s\n", message)

			if messageType == websocket.TextMessage {
				msg := CursorMessage{}
				err := json.Unmarshal(message, &msg)
				if err != nil {
					log.Println("error parsing JSON:", err)
				} else {
					fmt.Printf("Point received - Type: %v X: %f, Y: %f\n", msg.T, msg.X, msg.Y)
					DoCursorFunc(msg)
				}
			}
		}
	}
}
